import json
import re

from django.conf import settings
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django_redis import get_redis_connection
from fdfs_client.client import Fdfs_client

from .models import User
from django.http import HttpResponseBadRequest, JsonResponse, HttpResponseRedirect, HttpResponse
from django.shortcuts import render

# Create your views here.
from django.views import View


class RegisterView(View):
    def get(self, request):
        """渲染注册页面"""
        return render(request, 'register.html', {})

    def post(self, request):
        """处理注册用户请求"""

        # 获取数据
        recv_dict = json.loads(request.body)
        mobile = recv_dict.get('mobile')
        phonecode = recv_dict.get('phonecode')
        password = recv_dict.get('password')

        # 校验数据
        if not all([mobile, phonecode, password]):
            return HttpResponseBadRequest("missing argument")

        if not re.match(r'1[35789]\d{9}$', mobile):
            return HttpResponseBadRequest("illegal mobile")

        # 验证短信验证码
        redis_client = get_redis_connection('verify')
        sms_code = redis_client.get('sms_code_%s' % mobile)

        if sms_code:
            sms_code = sms_code.decode()

        if str(sms_code) != str(phonecode):
            return HttpResponseBadRequest('error sms code')

        redis_client.delete('sms_code_%s' % mobile)

        # 创建用户
        try:
            user = User.objects.get(mobile=mobile)
        except:
            try:
                user = User.objects.get(username=mobile)
            except:
                user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
                login(request, user)
                return JsonResponse({'errno': 0, 'errmsg': '注册成功'})

        login(request, user)
        request.session.set_expiry(None)
        response = HttpResponseRedirect('/')
        response.set_cookie('username', user.username)

        return response

def home_view(request):
    context = {
        'houses': [],
        'areas': []
    }
    return render(request, 'index.html', context=context)


class LoginView(View):
    def get(self, request):
        """判断是否登录"""
        user = request.user

        if user.is_authenticated:
            res = {
                'errno': 0,
                'errmsg': '已登录',
                'data': {
                    'name': user.username
                }
            }
            request.session.set_expiry(None)
            response = JsonResponse(res)
            response.set_cookie('username', user.username, expires=3600*24*14)
            return response

        else:
            res = {
                'errno': 4101,
                'errmsg': '为登录'
            }
            return JsonResponse(res)

    def post(self, request):
        """认证用户并登录"""

        # 获取数据
        recv_data = json.loads(request.body)
        mobile = recv_data.get('mobile')
        password = recv_data.get('password')

        # 校验数据
        if not all([mobile, password]):
            return HttpResponseBadRequest('参数不全')

        from users.utils import MyModelBackend
        backend = MyModelBackend()
        user = backend.authenticate(request=request, username=mobile, password=password)

        if not user:
            res = {
                'errno': 9999,
                'errmsg': '用户名不存在或密码错误'
            }
            return JsonResponse(res)

        # 校验通过，用户登录成功
        request.session.set_expiry(None)
        login(request, user)
        res = {
            'errno': 0,
            'errmsg': '登录成功'
        }
        response = JsonResponse(res)
        response.set_cookie('username', mobile, expires=3600 * 24 * 14)

        return response

    def delete(self, request):
        """用户登出"""
        logout(request)

        res = {
            'errno': '0',
            'errmsg': '已登出'
        }
        response = JsonResponse(res)
        response.delete_cookie('username')
        return response


class ShowLoginView(View):
    def get(self, request):
        return render(request, 'login.html')


class UserCenterView(View):
    def get(self, request):
        """用户中心获取个人信息"""

        # 获取数据
        user = request.user

        # 验证用户是否登录
        if user.is_authenticated:
            try:
                avatar = user.avatar.url
            except:
                avatar = ''
            res = {
                'data': {
                    'avatar_url': avatar,
                    'create_time': user.create_time,
                    'mobile': user.mobile,
                    'name': user.username,
                    'user_id': user.id
                },
                'errmsg': 'OK',
                'errno': '0'
            }
            return JsonResponse(res)

        else:
            res = {
                'errno': '4101',
                'errmsg': '未登录'
            }
            return JsonResponse(res)


class ShowUserCenterView(View):
    def get(self, request):
        return render(request, 'my.html')


class ShowProfileView(View):
    def get(self, request):
        return render(request, 'profile.html')


class UploadAvatarView(LoginRequiredMixin, View):
    def post(self, request):
        """上传头像"""

        avatar = request.FILES.get('avatar')
        user = request.user

        if not avatar:
            return HttpResponseBadRequest('未选择图片')

        client = Fdfs_client(settings.CONFIG_URL)
        buffer = avatar.read()
        result = client.upload_by_buffer(buffer)

        if result['Status'] != 'Upload successed.':
            return HttpResponseBadRequest('图片上传失败')

        avatar_url = result['Remote file_id']
        user.avatar = avatar_url
        user.save()

        res = {
            'data': {
                'avatar_url': settings.BASE_URL + avatar_url,
                'errno': '0',
                'errmsg': '头像上传成功'
            }
        }
        return JsonResponse(res)


class UpdateNameView(LoginRequiredMixin, View):
    def put(self, request):
        """修改用户名"""

        # 接受数据
        name = json.loads(request.body).get('name')
        user = request.user

        if not name:
            return JsonResponse({'errmsg': '修改失败', 'errno': 4101}, status=400)

        user.username = name
        user.save()

        return JsonResponse({'errno': 0, 'errmsg': '修改成功'}, status=201)


class RealNameAuthenticationView(LoginRequiredMixin, View):
    def post(self, request):
        """用户实名认证"""

        user = request.user
        real_name = json.loads(request.body).get('real_name')
        id_card = json.loads(request.body).get('id_card')

        if not all([real_name, id_card]):
            return JsonResponse({'errno': 4101, 'errmsg': '认证失败'})

        user.real_name = real_name
        user.id_card = id_card
        user.save()

        res = {
            'errno': 0,
            'errmsg': '认证信息保存成功'
        }
        return JsonResponse(res, status=201)
